<!-- 省市区选择组件 -->
<template>
  <view class="city-picker">
    <!-- 触发按钮 -->
    <view 
      class="flex items-center justify-between px-3 bg-white rounded-[12rpx] border border-solid border-gray-200 min-h-[88rpx] transition-all duration-200"
      :class="{
        'cursor-pointer active:bg-gray-50': !props.disabled,
        'opacity-50 cursor-not-allowed bg-gray-100': props.disabled
      }"
      @click="props.disabled ? null : showPicker()"
    >
      <text class="text-[28rpx] flex-1" :class="props.disabled ? 'text-gray-400' : 'text-gray-700'">
        {{ displayText }}
      </text>
      <IconFont 
        name="arrow-down" 
        size="12" 
        :class="props.disabled ? 'text-gray-300' : 'text-gray-400'" 
        class="ml-4" 
      />
    </view>

    <!-- 省市区选择弹窗 -->
    <nut-popup
      v-model:visible="showPopup"
      position="bottom"
      round
      :close-on-click-overlay="true"
      @close="handleClose"
    >
      <view class="bg-white rounded-t-3xl overflow-hidden max-h-[80vh] flex flex-col">
        <!-- 标题栏 -->
        <view class="flex items-center justify-between px-6 py-4 border-b border-gray-100 bg-white sticky top-0 z-10">
          <view class="text-[32rpx] font-semibold text-gray-900">{{ title }}</view>
          <view 
            class="w-[48rpx] h-[48rpx] flex items-center justify-center rounded-full bg-gray-100 text-gray-500 cursor-pointer transition-colors duration-200 active:bg-gray-200"
            @click="handleClose"
          >
            <IconFont name="close" size="32rpx" />
          </view>
        </view>

        <!-- 选择器内容 -->
        <view class="flex-1 flex overflow-hidden">
          <!-- 省份选择 -->
          <view class="flex-1 flex flex-col min-w-0 border-r border-gray-100">
            <view class="px-6 py-3 text-[24rpx] text-gray-500 bg-gray-50 border-b border-gray-100 sticky top-0 z-5">
              选择省份
            </view>
            <scroll-view class="flex-1 overflow-y-auto max-h-[60vh]" scroll-y>
              <view
                v-for="province in provinceList"
                :key="province.code"
                class="flex items-center justify-between px-6 py-1 border-b border-gray-50 cursor-pointer transition-all duration-200 min-h-[88rpx] active:bg-blue-50"
                :class="{ 'bg-blue-50 border-blue-200': selectedProvince?.code === province.code }"
                @click="selectProvince(province)"
              >
                <text 
                  class="text-[28rpx] text-gray-700 flex-1"
                  :class="{ 'text-blue-600 font-medium': selectedProvince?.code === province.code }"
                >
                  {{ province.name }}
                </text>
                <IconFont
                  v-if="selectedProvince?.code === province.code"
                  name="check"
                  size="32rpx"
                  class="text-blue-600 ml-4"
                />
              </view>
            </scroll-view>
          </view>

          <!-- 城市选择 -->
          <view 
            v-if="mode === 'city'" 
            class="flex-1 flex flex-col min-w-0"
          >
            <view class="px-6 py-3 text-[24rpx] text-gray-500 bg-gray-50 border-b border-gray-100 sticky top-0 z-5">
              选择城市
            </view>
            
            <!-- 加载状态 -->
            <view v-if="loading" class="flex-1 flex items-center justify-center text-gray-400">
              <view class="text-center">
                <IconFont name="loading" size="48rpx" class="animate-spin mb-4" />
                <text class="text-[28rpx]">正在加载城市数据...</text>
              </view>
            </view>
            
            <!-- 城市列表 -->
            <scroll-view v-else-if="cityList.length > 0" class="flex-1 overflow-y-auto max-h-[60vh]" scroll-y>
              <view
                v-for="city in cityList"
                :key="city.code"
                class="flex items-center justify-between px-6 py-1 border-b border-gray-50 cursor-pointer transition-all duration-200 min-h-[88rpx] active:bg-blue-50"
                :class="{ 'bg-blue-50 border-blue-200': selectedCity?.code === city.code }"
                @click="selectCity(city)"
              >
                <text 
                  class="text-[28rpx] text-gray-700 flex-1"
                  :class="{ 'text-blue-600 font-medium': selectedCity?.code === city.code }"
                >
                  {{ city.name }}
                </text>
                <IconFont
                  v-if="selectedCity?.code === city.code"
                  name="check"
                  size="32rpx"
                  class="text-blue-600 ml-4"
                />
              </view>
            </scroll-view>
            
            <!-- 未选择省份时的提示 -->
            <view v-else-if="!selectedProvince" class="flex-1 flex flex-col items-center justify-center text-gray-400">
              <IconFont name="location" size="64rpx" class="mb-4" />
              <text class="text-[28rpx]">请先选择省份</text>
            </view>
          </view>
        </view>

        <!-- 确认按钮 -->
        <view class="p-6 bg-white border-t border-gray-100 sticky bottom-0 z-10">
          <view 
            class="w-full h-[88rpx] bg-blue-600 rounded-2xl flex items-center justify-center cursor-pointer transition-all duration-200 active:bg-blue-700 active:scale-95"
            @click="handleConfirm"
          >
            <text class="text-[32rpx] font-medium text-white">确认</text>
          </view>
        </view>
      </view>
    </nut-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { IconFont } from '@nutui/icons-vue-taro'

/**
 * 省市区数据类型定义
 */
interface RegionData {
  code: string
  name: string
  level: number
  parentCode?: string
}

/**
 * 选择结果类型定义
 */
interface SelectionResult {
  province?: RegionData
  city?: RegionData
}

/**
 * 组件Props类型定义
 */
interface Props {
  /** 选择模式：province-仅选择省份，city-选择省市 */
  mode?: 'province' | 'city'
  /** 占位符文本 */
  placeholder?: string
  /** 弹窗标题 */
  title?: string
  /** 默认选中的省份代码 */
  defaultProvinceCode?: string
  /** 默认选中的城市代码 */
  defaultCityCode?: string
  /** 是否禁用 */
  disabled?: boolean
}

/**
 * 组件Emits类型定义
 */
interface Emits {
  /** 选择完成事件 */
  (e: 'confirm', result: SelectionResult): void
  /** 取消选择事件 */
  (e: 'cancel'): void
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'province',
  placeholder: '请选择地区',
  title: '地区选择',
  defaultProvinceCode: '',
  defaultCityCode: '',
  disabled: false
})

const emit = defineEmits<Emits>()

// 响应式数据
const showPopup = ref(false)
const provinceList = ref<RegionData[]>([])
const cityList = ref<RegionData[]>([])
const selectedProvince = ref<RegionData | null>(null)
const selectedCity = ref<RegionData | null>(null)
const loading = ref(false) // 加载状态
const isConfirming = ref(false) // 标志位，用于区分确认关闭和取消关闭

/**
 * 显示文本计算属性
 * @returns 显示在触发按钮上的文本
 */
const displayText = computed(() => {
  if (selectedCity.value) {
    return `${selectedProvince.value?.name} ${selectedCity.value.name}`
  }
  if (selectedProvince.value) {
    return selectedProvince.value.name
  }
  return props.placeholder
})

/**
 * 获取省市区数据（优先使用接口，失败时使用静态数据）
 */
const fetchRegionData = async (parentCode = '0'): Promise<RegionData[]> => {
  try {
    if (parentCode === '0') {
      // 省份数据直接使用静态数据
      return getStaticRegionData(parentCode)
    } else {
      // 城市数据优先从接口获取
      const response = await fetch(`https://datavmap-public.oss-cn-hangzhou.aliyuncs.com/areas/csv/${parentCode}_city.json`)
      if (response.ok) {
        const data = await response.json()
        if (data.rows && Array.isArray(data.rows)) {
          return data.rows.map((item: any) => ({
            code: item.adcode,
            name: item.name,
            level: 2,
            parentCode: parentCode
          }))
        }
      }
      throw new Error('接口请求失败')
    }
  } catch (error) {
    console.warn('从接口获取城市数据失败，使用静态数据:', error)
    // 接口失败时使用静态数据作为备用
    return getStaticRegionData(parentCode)
  }
}

/**
 * 静态省市区数据（主要数据源）
 * 包含全国所有省份和主要城市数据
 * @param parentCode 父级代码
 * @returns 区域数据列表
 */
const getStaticRegionData = (parentCode: string): RegionData[] => {
  if (parentCode === '0') {
    // 省份数据
    return [
      { code: '110000', name: '北京市', level: 1 },
      { code: '120000', name: '天津市', level: 1 },
      { code: '130000', name: '河北省', level: 1 },
      { code: '140000', name: '山西省', level: 1 },
      { code: '150000', name: '内蒙古自治区', level: 1 },
      { code: '210000', name: '辽宁省', level: 1 },
      { code: '220000', name: '吉林省', level: 1 },
      { code: '230000', name: '黑龙江省', level: 1 },
      { code: '310000', name: '上海市', level: 1 },
      { code: '320000', name: '江苏省', level: 1 },
      { code: '330000', name: '浙江省', level: 1 },
      { code: '340000', name: '安徽省', level: 1 },
      { code: '350000', name: '福建省', level: 1 },
      { code: '360000', name: '江西省', level: 1 },
      { code: '370000', name: '山东省', level: 1 },
      { code: '410000', name: '河南省', level: 1 },
      { code: '420000', name: '湖北省', level: 1 },
      { code: '430000', name: '湖南省', level: 1 },
      { code: '440000', name: '广东省', level: 1 },
      { code: '450000', name: '广西壮族自治区', level: 1 },
      { code: '460000', name: '海南省', level: 1 },
      { code: '500000', name: '重庆市', level: 1 },
      { code: '510000', name: '四川省', level: 1 },
      { code: '520000', name: '贵州省', level: 1 },
      { code: '530000', name: '云南省', level: 1 },
      { code: '540000', name: '西藏自治区', level: 1 },
      { code: '610000', name: '陕西省', level: 1 },
      { code: '620000', name: '甘肃省', level: 1 },
      { code: '630000', name: '青海省', level: 1 },
      { code: '640000', name: '宁夏回族自治区', level: 1 },
      { code: '650000', name: '新疆维吾尔自治区', level: 1 }
    ]
  }
  
  // 主要城市数据（降级方案）
  const cityMap: Record<string, RegionData[]> = {
    '110000': [
      { code: '110100', name: '北京市', level: 2, parentCode: '110000' }
    ],
    '120000': [
      { code: '120100', name: '天津市', level: 2, parentCode: '120000' }
    ],
    '310000': [
      { code: '310100', name: '上海市', level: 2, parentCode: '310000' }
    ],
    '440000': [
      { code: '440100', name: '广州市', level: 2, parentCode: '440000' },
      { code: '440300', name: '深圳市', level: 2, parentCode: '440000' },
      { code: '440600', name: '佛山市', level: 2, parentCode: '440000' },
      { code: '441900', name: '东莞市', level: 2, parentCode: '440000' }
    ],
    '320000': [
      { code: '320100', name: '南京市', level: 2, parentCode: '320000' },
      { code: '320200', name: '无锡市', level: 2, parentCode: '320000' },
      { code: '320300', name: '徐州市', level: 2, parentCode: '320000' },
      { code: '320400', name: '常州市', level: 2, parentCode: '320000' },
      { code: '320500', name: '苏州市', level: 2, parentCode: '320000' }
    ],
    '410000': [
      { code: '410100', name: '郑州市', level: 2, parentCode: '410000' },
      { code: '410200', name: '开封市', level: 2, parentCode: '410000' },
      { code: '410300', name: '洛阳市', level: 2, parentCode: '410000' },
      { code: '410400', name: '平顶山市', level: 2, parentCode: '410000' },
      { code: '410500', name: '安阳市', level: 2, parentCode: '410000' },
      { code: '410600', name: '鹤壁市', level: 2, parentCode: '410000' },
      { code: '410700', name: '新乡市', level: 2, parentCode: '410000' },
      { code: '410800', name: '焦作市', level: 2, parentCode: '410000' },
      { code: '410900', name: '濮阳市', level: 2, parentCode: '410000' },
      { code: '411000', name: '许昌市', level: 2, parentCode: '410000' },
      { code: '411100', name: '漯河市', level: 2, parentCode: '410000' },
      { code: '411200', name: '三门峡市', level: 2, parentCode: '410000' },
      { code: '411300', name: '南阳市', level: 2, parentCode: '410000' },
      { code: '411400', name: '商丘市', level: 2, parentCode: '410000' },
      { code: '411500', name: '信阳市', level: 2, parentCode: '410000' },
      { code: '411600', name: '周口市', level: 2, parentCode: '410000' },
      { code: '411700', name: '驻马店市', level: 2, parentCode: '410000' },
      { code: '419001', name: '济源市', level: 2, parentCode: '410000' }
    ]
  }
  
  return cityMap[parentCode] || []
}

/**
 * 初始化省份数据
 */
const initProvinceData = async () => {
  loading.value = true
  try {
    provinceList.value = await fetchRegionData('0')
    
    // 如果有默认选中的省份，则选中它
    if (props.defaultProvinceCode) {
      const defaultProvince = provinceList.value.find(p => p.code === props.defaultProvinceCode)
      if (defaultProvince) {
        selectedProvince.value = defaultProvince
        
        // 如果是城市模式，加载对应城市数据
        if (props.mode === 'city') {
          await loadCityData(props.defaultProvinceCode)
        }
      }
    }
  } finally {
    loading.value = false
  }
}

/**
 * 加载城市数据
 * @param provinceCode 省份代码
 */
const loadCityData = async (provinceCode: string) => {
  loading.value = true
  try {
    cityList.value = await fetchRegionData(provinceCode)
    
    // 如果有默认选中的城市，则选中它
    if (props.defaultCityCode) {
      const defaultCity = cityList.value.find(c => c.code === props.defaultCityCode)
      if (defaultCity) {
        selectedCity.value = defaultCity
      }
    }
  } finally {
    loading.value = false
  }
}

/**
 * 显示选择器
 */
const showPicker = () => {
  showPopup.value = true
}

/**
 * 选择省份
 * @param province 选中的省份
 */
const selectProvince = async (province: RegionData) => {
  selectedProvince.value = province
  selectedCity.value = null // 重置城市选择
  
  // 如果是城市模式，加载对应城市数据
  if (props.mode === 'city') {
    await loadCityData(province.code)
  }
}

/**
 * 选择城市
 * @param city 选中的城市
 */
const selectCity = (city: RegionData) => {
  selectedCity.value = city
}

/**
 * 确认选择
 */
const handleConfirm = () => {
  if (!selectedProvince.value) {
    return
  }
  
  if (props.mode === 'city' && !selectedCity.value) {
    return
  }
  
  const result: SelectionResult = {
    province: selectedProvince.value
  }
  
  if (props.mode === 'city' && selectedCity.value) {
    result.city = selectedCity.value
  }
  
  // 设置确认标志位，避免触发cancel事件
  isConfirming.value = true
  emit('confirm', result)
  showPopup.value = false
}

/**
 * 关闭弹窗
 */
const handleClose = () => {
  showPopup.value = false
  
  // 只有在不是确认操作时才发出cancel事件
  if (!isConfirming.value) {
    emit('cancel')
  }
  
  // 重置确认标志位
  isConfirming.value = false
}

// 监听模式变化，重置选择状态
watch(() => props.mode, (newMode) => {
  if (newMode === 'province') {
    selectedCity.value = null
    cityList.value = []
  }
})

// 组件挂载时初始化数据
onMounted(async () => {
  await initProvinceData()
})
</script>